import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:html/parser.dart';
import 'package:yhdm_mobile/constants.dart';
import 'package:yhdm_mobile/page/home/home_entity.dart';
import 'package:yhdm_mobile/utils/route_utils.dart';

import '../home_page.dart';

class AnimSearchDelegate extends SearchDelegate<String> {
  var hint = '请输入关键字';

  var host = 'http://m.yhdm.tv';

  SearchEntity searchEntity = SearchEntity();

  @override
  String get searchFieldLabel => hint;

  @override
  TextStyle get searchFieldStyle => TextStyle(color: Colors.white54);

  @override
  ThemeData appBarTheme(BuildContext context) {
    return super.appBarTheme(context).copyWith(
        primaryColor: primaryColor,
        textTheme: Theme.of(context).textTheme.copyWith(
            headline6: Theme.of(context)
                .textTheme
                .headline6
                .copyWith(color: Colors.white)));
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: AnimatedIcon(
          icon: AnimatedIcons.menu_close,
          progress: transitionAnimation,
          color: Colors.white,
        ),

        ///调用 close 关闭 search 界面
        onPressed: () => close(context, null),
      )
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: AnimatedIcon(
        icon: AnimatedIcons.menu_arrow,
        progress: transitionAnimation,
        color: Colors.white,
      ),

      ///调用 close 关闭 search 界面
      onPressed: () => close(context, null),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    var keywords = query;
    var response = getSearchResultList(keywords);
    response.then((value) {
      // context.read<SearchEntity>().setData(value);
    });
    return FutureBuilder(
        future: response,
        builder:
            (BuildContext contex, AsyncSnapshot<List<AnimeEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return SingleChildScrollView(
              child: Column(
                children: [
                  SizedBox(height: 10),
                  Container(
                    child: Center(
                      child: Wrap(
                        spacing: 5,
                        runSpacing: 5,
                        children: [
                          ...buildCardList(context, snapshot.data),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(height: 20),
                ],
              ),
            );
          } else {
            return Center(
              child: CircularProgressIndicator(
                semanticsLabel: '加载中...',
              ),
            );
          }
        });
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return Container();
  }

  List<Widget> buildCardList(
      BuildContext context, List<AnimeEntity> classList) {
    var list = List<Widget>();
    classList.forEach((element) {
      list.add(AnimeCardWidget(
        name: element.name,
        imageUrl: element.imageUrl,
        episode: element.episode,
        onImageTap: () {
          RouteUtils.openPage(context, element.url, element.name);
        },
        onNameTap: () {
          RouteUtils.openPage(context, element.url, element.name);
        },
      ));
    });
    return list;
  }

  Future<List<AnimeEntity>> getSearchResultList(String keywords) async {
    Dio dio = Dio();
    var value =
        await dio.get<String>('http://m.yhdm.tv/search/' + keywords + '/');
    var html = value.data;
    var document = parse(html); //body > div.tlist > ul:nth-child(1)
    var div = document
        .getElementsByClassName('listtit')[0]
        .parent; // body > div:nth-child(4)
    div.children.removeAt(0);
    var animeList = List<AnimeEntity>();
    div.children.forEach((element) {
      element.children.forEach((e) {
        var itemtext = e.getElementsByClassName('itemtext')[0];
        var url = host + itemtext.attributes['href'];
        var name = itemtext.text;
        var itemimgtext = e.getElementsByClassName('itemimgtext')[0];
        var episode = itemimgtext.text;
        var imgblock = e.getElementsByClassName('imgblock')[0];
        var style = imgblock.attributes['style'];
        var imageUrl =
            style.substring(style.indexOf("http://"), style.lastIndexOf("')"));
        var animeEntity = AnimeEntity(url, imageUrl, name, episode: episode);
        animeList.add(animeEntity);
      });
    });
    return animeList;
  }
}
